package com.cefa.finance.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cefa.finance.config.ConstantProperties;
import com.cefa.finance.dao.*;
import com.cefa.finance.model.*;
import com.cefa.finance.utils.HttpClientUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@SuppressWarnings("ALL")
@Service
public class BlockChainService {

    private static final Logger logger = LoggerFactory.getLogger(BlockChainService.class);

    @Autowired
    private AccountRepository accountRepository;

    @Autowired
    private ConstantProperties constantProperties;

    public Account getWallet() {
        Account account = null;
        try {
            String response = HttpClientUtils.doHttpPostRequest(constantProperties.newWalletUrl, null, null);
            logger.info("初始化用户钱包------" + response);

            if (response != null && !"".equals(response)) {
                JSONObject jsonObject = JSON.parseObject(response);
                Integer code = jsonObject.getInteger("err");
                if (code == 0) {
                    String msg = jsonObject.getString("msg");
                    account = JSON.parseObject(msg, Account.class);
                } else {
                    logger.error("初始化用户钱包出错------" + response);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("初始化用户钱包出错------", e.getMessage());
        }
        return account;
    }


    public String getFileAddress(Long loginUserId) {
        String fileAddress = null;
        try {
            Account loginUser = accountRepository.findOne(loginUserId);
            HashMap<String, String> condition = new HashMap<>();

            if (loginUser.getPrikey() != null && loginUser.getAddress() != null) {

                condition.put("userAddress", loginUser.getAddress());
                condition.put("prikey", loginUser.getPrikey());
                String response = HttpClientUtils.doHttpPostRequest(constantProperties.deployfileUrl, null, condition);
                logger.info("获取FileAddress------" + response);

                if (response != null && !"".equals(response)) {
                    JSONObject jsonObject = JSON.parseObject(response);
                    Integer code = jsonObject.getInteger("err");

                    if (code != null && code == 0) {
                        fileAddress = jsonObject.getString("msg");
                    } else {
                        logger.error("获取FileAddress出错------" + response);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取FileAddress出错------", e.getMessage());
        }
        return fileAddress;
    }


    public String tostableJSON(String sourceJson) {
        String stableJSON = null;
        try {
            HashMap<String, String> condition = new HashMap<>();
            condition.put("json", sourceJson);

            String response = HttpClientUtils.doHttpPostRequest(constantProperties.tostableJsonUrl, null, condition);
            logger.info("json转换------" + response);

            if (response != null && !"".equals(response)) {
                JSONObject jsonObject = JSON.parseObject(response);
                Integer code = jsonObject.getInteger("err");

                if (code != null && code == 0) {
                    stableJSON = jsonObject.getString("msg");
                } else {
                    logger.error("json转换------------" + response);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("json转换出错------", e.getMessage());
        }
        return stableJSON;
    }


    public User putUserInfoOnBlockchain(String prikey, String fileAddress, String stableJson) {
        User user = null;
        try {
            HashMap<String, String> condition = new HashMap<>();
            condition.put("prikey", prikey);
            condition.put("fileAddress", fileAddress);
            condition.put("stablejson", stableJson);

            String response = HttpClientUtils.doHttpPostRequest(constantProperties.addfilerecordUrl, null, condition);
            logger.info("上链用户信息------" + response);

            if (response != null && !"".equals(response)) {
                JSONObject jsonObject = JSON.parseObject(response);
                Integer code = jsonObject.getInteger("err");

                if (code != null && code == 0) {
                    String msg = jsonObject.getString("msg");
                    user = JSON.parseObject(msg, User.class);
                } else {
                    logger.error("上链用户信息出错----------" + response);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("上链用户信息出错------", e.getMessage());
        }
        return user;
    }

    public Vehicle putVehicleInfoOnBlockchain(String prikey, String fileAddress, String stableJson) {
        Vehicle vehicle = null;
        try {
            HashMap<String, String> condition = new HashMap<>();
            condition.put("prikey", prikey);
            condition.put("fileAddress", fileAddress);
            condition.put("stablejson", stableJson);

            String response = HttpClientUtils.doHttpPostRequest(constantProperties.addfilerecordUrl, null, condition);
            logger.info("上链车辆信息------" + response);

            if (response != null && !"".equals(response)) {
                JSONObject jsonObject = JSON.parseObject(response);
                Integer code = jsonObject.getInteger("err");

                if (code != null && code == 0) {
                    String msg = jsonObject.getString("msg");
                    vehicle = JSON.parseObject(msg, Vehicle.class);
                } else {
                    logger.error("上链车辆信息出错----------" + response);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("上链车辆信息出错------", e.getMessage());
        }
        return vehicle;
    }


    public FileContractBlockData uploadContractOnBlockchain(String prikey, String fileAddress, String hashfile) {
        FileContractBlockData fileContract = null;
        try {
            HashMap<String, String> condition = new HashMap<>();
            condition.put("prikey", prikey);
            condition.put("fileAddress", fileAddress);
            condition.put("sha3file", hashfile);

            String response = HttpClientUtils.doHttpPostRequest(constantProperties.uploadContractUrl, null, condition);
            logger.info("上链合同记录信息------" + response);

            if (response != null && !"".equals(response)) {
                JSONObject jsonObject = JSON.parseObject(response);
                Integer code = jsonObject.getInteger("err");

                if (code != null && code == 0) {
                    String msg = jsonObject.getString("msg");
                    fileContract = JSON.parseObject(msg, FileContractBlockData.class);
                } else {
                    logger.error("上链合同记录信息出错----------" + response);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("上链合同记录信息出错------", e.getMessage());
        }
        return fileContract;
    }


    public String ToSha3(String fileString) {

        String sha3String = null;
        try {
            HashMap<String, String> condition = new HashMap<>();
            condition.put("stablejson", fileString);

            String response = HttpClientUtils.doHttpPostRequest(constantProperties.toSha3Url, null, condition);
            logger.info("获取sha3值------" + response);

            if (response != null && !"".equals(response)) {
                JSONObject jsonObject = JSON.parseObject(response);
                Integer code = jsonObject.getInteger("err");

                if (code != null && code == 0) {
                    sha3String = jsonObject.getString("msg");
                } else {
                    logger.error("获取sha3值出错----------" + response);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取sha3值出错------", e.getMessage());
        }
        return sha3String;
    }
}